package com.huan.social.weixin.api.impl;

import com.google.gson.Gson;
import com.huan.social.weixin.api.Weixin;
import com.huan.social.weixin.api.WeixinUserInfo;
import lombok.Getter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * 微信接口实现，用于获取微信用户信息
 *
 * @author huan.fu
 * @date 2018/9/27 - 11:09
 */
public class WeixinTemplate extends AbstractOAuth2ApiBinding implements Weixin {

	/**
	 * 获取用户信息的url
	 */
	@Getter
	private String userInfoUrl;

	public WeixinTemplate(String userInfoUrl, String accessToken) {
		/**
		 * 调用父类 2 个参数的构造方法，
		 * TokenStrategy.ACCESS_TOKEN_PARAMETER这种策略表示会自动将 oauth_token 放入到请求参数中
		 */
		super(accessToken, TokenStrategy.OAUTH_TOKEN_PARAMETER);
		this.userInfoUrl = userInfoUrl;
	}


	@Override
	public WeixinUserInfo getUserInfo(String openId) {
		String url = String.format(this.getUserInfoUrl(), openId);
		return new Gson().fromJson(getRestTemplate().getForObject(url, String.class), WeixinUserInfo.class);
	}

	/**
	 * 防止返回值乱码
	 *
	 * @param restTemplate
	 */
	@Override
	protected void configureRestTemplate(RestTemplate restTemplate) {
		restTemplate.getMessageConverters().forEach(convert -> {
			if (convert instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) convert).setDefaultCharset(StandardCharsets.UTF_8);
			}
		});
	}
}
